<template>
  <div class="customer-service">
    <!-- 客服按钮 -->
    <div class="cs-button" @click="toggleChat" :class="{ active: isOpen }">
      <el-badge :value="unreadCount" :hidden="unreadCount === 0">
        <el-icon size="24"><Service /></el-icon>
      </el-badge>
    </div>

    <!-- 聊天窗口 -->
    <div class="chat-window" v-show="isOpen">
      <div class="chat-header">
        <span>在线客服</span>
        <el-icon class="close-btn" @click="toggleChat"><Close /></el-icon>
      </div>

      <div class="chat-messages" ref="messageContainer">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.type === 'user' ? 'user-message' : 'cs-message']"
        >
          <div class="avatar">
            <el-avatar :size="32" :src="message.type === 'user' ? userAvatar : csAvatar" />
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.time) }}</div>
          </div>
        </div>
      </div>

      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          placeholder="请输入消息..."
          @keyup.enter="sendMessage"
          :disabled="sending"
        >
          <template #append>
            <el-button @click="sendMessage" :loading="sending">发送</el-button>
          </template>
        </el-input>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import { Service, Close } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import dayjs from 'dayjs'

interface Message {
  content: string
  type: 'user' | 'cs'
  time: Date
}

const userStore = useUserStore()
const isOpen = ref(false)
const messages = ref<Message[]>([])
const inputMessage = ref('')
const sending = ref(false)
const unreadCount = ref(0)
const messageContainer = ref<HTMLElement>()

const userAvatar = userStore.userDetail?.avatar || '/default-avatar.png'
const csAvatar = '/cs-avatar.png'

// 切换聊天窗口
const toggleChat = () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    unreadCount.value = 0
    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || sending.value) return

  sending.value = true
  const userMessage: Message = {
    content: inputMessage.value,
    type: 'user',
    time: new Date(),
  }
  messages.value.push(userMessage)
  inputMessage.value = ''

  // 模拟客服回复
  setTimeout(() => {
    const csMessage: Message = {
      content: '您好，请问有什么可以帮您？',
      type: 'cs',
      time: new Date(),
    }
    messages.value.push(csMessage)
    sending.value = false
    if (!isOpen.value) {
      unreadCount.value++
    }
  }, 1000)

  await nextTick()
  scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (time: Date) => {
  return dayjs(time).format('HH:mm')
}

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

// 初始化欢迎消息
onMounted(() => {
  messages.value.push({
    content: '您好！请问有什么可以帮您？',
    type: 'cs',
    time: new Date(),
  })
})
</script>

<style scoped>
.customer-service {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
}

.cs-button {
  width: 48px;
  height: 48px;
  background: var(--el-color-primary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.cs-button:hover {
  transform: scale(1.1);
}

.cs-button.active {
  background: var(--el-color-primary-light-3);
}

.chat-window {
  position: absolute;
  right: 60px;
  bottom: 0;
  width: 320px;
  height: 480px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 12px 16px;
  background: var(--el-color-primary);
  color: white;
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  cursor: pointer;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.message {
  display: flex;
  margin-bottom: 16px;
  gap: 8px;
}

.message-content {
  max-width: 70%;
}

.message-text {
  padding: 8px 12px;
  border-radius: 8px;
  word-break: break-word;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.user-message {
  flex-direction: row-reverse;
}

.user-message .message-text {
  background: var(--el-color-primary-light-8);
  color: var(--el-color-primary);
}

.cs-message .message-text {
  background: #f4f4f5;
  color: #333;
}

.chat-input {
  padding: 16px;
  border-top: 1px solid #eee;
}
</style>
